import base64
import os
import random
import time

from django.conf import settings
from django.contrib import admin
from lxml import etree

from projectdeploy.models import Command, VodHost, Wiki, Fileupload, \
    HostSystemAccount
from projectdeploy.utils import SSHConnection


admin.site.site_header = '艾美歌库集群管理系统'
admin.site.site_title = '艾美歌库集群管理系统'

# Register your models here.
@admin.register(Command)
class CommandAdmin(admin.ModelAdmin):
    list_display = ('exec_command','exec_user','exec_result','exec_time',)
    filter_horizontal=('exec_dst_host',)
    
    fieldsets = (
        ('执行信息',{
        'fields':('exec_command','exec_dst_host',)
        }),
        ('执行结果',{
        'fields':('exec_result','exec_result_detail',)
        }),
    )
    readonly_fields = ('exec_result', 'exec_result_detail',)
    list_per_page = 20
    search_fields = ('exec_command',)
    
    change_form_template = 'projectdeploy/command_change_form.html'
    
    def has_delete_permission(self, request, obj=None):
        return False
    
    def has_change_permission(self, request, obj=None):
        return False
    
    
    def save_model(self, request, obj, form, change):
        exec_dst_host = form.cleaned_data['exec_dst_host']
        result_list = []
        exec_result = 0
        for vhost in exec_dst_host:
            username = vhost.vod_account.username
            pwd = vhost.vod_account.pwd
            result_list.append("【"+vhost.vod_ip+"】")
            try:
                ssh = SSHConnection(host=vhost.vod_ip,port=vhost.vod_ssh_port,username=username,pwd=pwd)
                ssh.connect()
                sin,sout,serr = ssh.cmd(obj.exec_command)
            except Exception as e:
                serr = str(e)
            if serr:
                result_list.append(':failure\n')
                result_list.append(serr)
                exec_result= 1
            else:
                result_list.append(":success\n")
                result_list.append(sout)
                result_list.append("\n")
        obj.exec_user = request.user
        obj.exec_result = exec_result
        obj.exec_result_detail = "".join(result_list)
        admin.ModelAdmin.save_model(self, request, obj, form, change)
    
@admin.register(VodHost)
class VodHostAdmin(admin.ModelAdmin):
    list_display = ('vod_hostname','vod_ip','vod_online','vod_account','vod_ssh_port','vod_description')
    fieldsets = (
        ('主机信息',{
        'fields':('vod_hostname','vod_ip','vod_account','vod_ssh_port','vod_description',)
        }),
    )

@admin.register(Wiki)
class Wikiadmin(admin.ModelAdmin):
    list_display = ('title',)
    list_filter = ('title',)
    search_fields = ('title','contentarea',)
    change_form_template = 'projectdeploy/change_wiki.html'
    
    def save_model(self, request, obj, form, change):
        tree = etree.HTML(obj.contentarea)
        images = tree.xpath("//img/@src")
        for image in images:
            imagecontent = image.split(";base64,")
            if len(imagecontent) > 1:
                imagename = str(int(time.time()*1000))+str(random.randint(1,1000))
                suffix = imagecontent[0].split("/")[1]
                imagesaveurl = os.path.join(settings.MEDIA_ROOT,imagename+"."+suffix)
                imagegeturl = "http://"+request.get_host()+os.path.join(settings.MEDIA_URL,imagename+"."+suffix)
                with open(imagesaveurl,'wb') as imagefile:
                    imagefile.write(base64.b64decode(imagecontent[1]))
                obj.contentarea = obj.contentarea.replace(image,imagegeturl)  
        admin.ModelAdmin.save_model(self, request, obj, form, change)

@admin.register(Fileupload)
class Fileuploadadmin(admin.ModelAdmin):
    fieldsets = (
        ('上传/下载',{
        'fields':('exec_type',('srcfile','dstfile'),'exec_dst_host')
        }),
        ('执行结果',{
        'fields':('exec_result','exec_result_detail',)
        }),
        
    )
    list_display = ('dstfile','uploaduser')
    readonly_fields = ('exec_result', 'exec_result_detail',)
    filter_horizontal=('exec_dst_host',)
    
    def has_change_permission(self, request, obj=None):
        return False
    
    def has_delete_permission(self, request, obj=None):
        return False
    
    change_form_template = 'projectdeploy/fileupload_change_form.html'
    
    def save_model(self, request, obj, form, change):
        obj.uploaduser = request.user
        filename = obj.srcfile
        admin.ModelAdmin.save_model(self, request, obj, form, change)
        print(obj.id)
        getfileurl = os.path.join(settings.MEDIA_ROOT,str(filename))
        exec_dst_host = form.cleaned_data['exec_dst_host']
        result_list = []
        if not change:
            exec_result = 0 
            for vhost in exec_dst_host:
                result_list.append("【"+vhost.vod_ip+"】")
                result_list.append(":\n")
                try:
                    username = vhost.vod_account.username
                    pwd = vhost.vod_account.pwd
                    ssh = SSHConnection(host=vhost.vod_ip,port=vhost.vod_ssh_port,username=username,pwd=pwd)
                    ssh.connect()
                    ssh.upload(getfileurl, obj.dstfile)
                    sin,sout,serr = ssh.cmd("ls -lrt " + obj.dstfile)
                    result_list.append(sout)
                    result_list.append("\n")
                except Exception as e:
                    exec_result = 1
                    errorcontent = str(e)
                    result_list.append(errorcontent +":\n")
                    if "Failure" in errorcontent:
                        result_list.append("可能原因：1.目标路径需要写上具体文件名;2.目标目录没有同名的文件夹;3.不能使用'~'符号\n")
                
            obj.exec_result_detail =  "".join(result_list)
            obj.exec_result = exec_result   
            obj.save()        
                          
@admin.register(HostSystemAccount)
class HostSystemAccountadmin(admin.ModelAdmin):
    list_display = ('name','username','description',)
    fieldsets = (
        ('账号信息',{
        'fields':('name','username','pwd','description')
        }),
    )
        
    